<template>
  <div class="app-container">
    <el-tabs v-model="listQuery.status" type="card" style="margin-bottom:10px">
      <el-tab-pane v-for="item in statusJson" :key="item.value" :label="item.label" :name="item.value+''">
      </el-tab-pane>
    </el-tabs>
    <div class="filter-container">
      <el-input v-model="listQuery.identifier" placeholder="单据编号" class="filter-item" clearable/>
      <el-select v-model="listQuery.type" class="filter-item" placeholder="委托类型" clearable>
        <el-option v-for="item in typeJson" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <!-- <el-input v-model="listQuery.companyName" placeholder="企业名称" class="filter-item" /> -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"
        >
        查询
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate"
        >
        添加
      </el-button>
    </div>
    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row row-key="id" style="width: 100%;">
      <el-table-column label="序号" type="index" align="center" width="60px" />
      <el-table-column label="单据编号" prop="identifier" align="center" />
      <el-table-column label="企业名称" prop="companyName" align="center" />
      <el-table-column label="委托类型" prop="typeText" align="center" />
      <el-table-column label="委托说明" prop="remark" align="center" />
      <el-table-column label="委托状态" prop="statusText" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.statusText }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220px">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleCancel(row)"
            v-if="row.status === 1 ">取消订单</el-button>
          <el-button size="mini" @click="handleDetail(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="88px"
        style="margin: 0 50px;">
        <el-form-item label="委托类型">
          <div>{{ userInfo.type === 1 ? "委托采购" : "委托销售" }}</div>
        </el-form-item>
        <el-form-item label="价格" v-if="userInfo.type === 1" prop="topPrice">
          <el-input type="number" v-model="temp.topPrice"></el-input>
        </el-form-item>
        <el-form-item label="委托说明" prop="remark">
          <el-input type="textarea" v-model="temp.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="saveData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="详情" :visible.sync="dialogDetailVisible" width="888px" v-if="detail">
      <el-row :gutter="40">
        <el-col :span="8">单据编号：<span style="font-size:13px">{{detail.identifier}}</span></el-col>
        <el-col :span="8">订单创建时间：<span style="font-size:14px">{{detail.createTime}}</span></el-col>
        <el-col :span="8">订单状态：{{detail.statusText}}</el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8" v-if="detail.handleRemark">
          订单确认意见：{{detail.handleRemark}}
        </el-col>
        <el-col :span="8" v-if="detail.handleName">
          订单确认人：{{detail.handleName}}
        </el-col>
      </el-row>
      <el-row :gutter="40" v-if="detail.handleImage">
        <el-col :span="24">
          订单确认凭证:
          <a style="color:#1890ff;text-decoration: underline" :href="orderDetail.handleImage" target="_blank">查看凭证</a>
          <!-- <el-image style="width: 100px; height: 100px" title="点击图片查看大图" :src="detail.handleImage	"
            :preview-src-list="[detail.handleImage]"></el-image> -->
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8">委托类型：{{detail.typeText}}</el-col>
        <el-col :span="8">
          企业名称：{{detail.companyName}}
        </el-col>
        <el-col v-if="detail.type === 3" :span="8">委托价格(元)：{{detail.topPrice}}</el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">委托说明：{{detail.remark}}</el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDetailVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogDetailVisible = false">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import { entrustPageByQo, entrustSave, entrustGetById, entrustCancel } from '@/api/transaction'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { statusJson, typeJson } from '../constant'

export default {
  name: 'Transaction',
  directives: { waves },
  components: { Pagination },
  filters: {
    statusFilter(status) { //状态
      const statusMap = {
        1: 'warning',
        2: '',
        3:'success',
        98: 'info',
        99: 'danger',
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        type: '',
        status: '1',
        pageNo: 1,
        pageSize: 20,
        identifier: '',
        companyName: ''
      },
      temp: {
        id: 0,
        type: '',
        topPrice:'',
        remark: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑交易',
        create: '添加交易'
      },
      rules: {
        // type: [{ required: true, message: '请选择', trigger: 'change' }],
        topPrice: [{ required: true, message: '请输入', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
      roleList: [],
      statusJson,
      typeJson,
      dialogDetailVisible: false,
      detail: {}
    }
  },
  watch: {
    'listQuery.status': function () {
      this.handleFilter()
    },
  },
  computed: {
    ...mapGetters(["userInfo","token"]),
  },
  created() {
    if (this.$route.query.status && this.listQuery.status !== this.$route.query.status.toString()) {
      this.listQuery.status = this.$route.query.status.toString()
    }
    if (this.$route.query.identifier) {
      this.listQuery.identifier = this.$route.query.identifier.toString();
    }
    
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      entrustPageByQo(this.listQuery).then(response => {
        this.list = response.list || []
        this.total = response.totalCount
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: 0,
        type: '',
        type: '',
        remark: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    saveData() {
      if (this.temp.type === 3) {
        let price = parseFloat(this.temp.topPrice);
        if (price <= 0) {
          this.$message.error("价格需大于0");
          return;
        }
      }

      if (this.userInfo.type === 1) {
        this.temp.type = 3
      } else {
        this.temp.type = 4
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const params = {
            type: this.temp.type,
            topPrice: this.temp.topPrice,
            remark: this.temp.remark
          }
          entrustSave(params).then(() => {
            this.getList()
            this.dialogFormVisible = false
            // this.$notify({
            //   title: '成功',
            //   message: '保存成功',
            //   type: 'success',
            //   duration: 2000
            // })

            this.$message({
              message: '保存成功',
              type: 'success'
            });
          })
        }
      })
    },
    handleDetail(row) {
      this.getDetail(row.id).then(res => {
        this.detail = Object.assign({}, res)
        this.dialogDetailVisible = true;
      })
    },
    getDetail(id) {
      return new Promise((resolve, reject) => {
        entrustGetById(id)
          .then(res => {
            resolve(res);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    handleCancel(row) {
      this.$confirm("是否确认取消订单？").then(() => {
        entrustCancel({ id: row.id }).then(() => {
          this.getList();
          // this.$notify({
          //   title: "成功",
          //   message: "操作成功",
          //   type: "success",
          //   duration: 2000,
          // });

          this.$message({
            message: '操作成功',
            type: 'success'
          });
        });
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.el-row {
  line-height: 2;
  font-size: 15px;
}
</style>
